package com.atguigu.gulimall.order.mqlistener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RabbitListener(queues = "order.release.order.queue")
public class CloseOrderListener {

    @Autowired
    private OrderService orderService;

    @RabbitHandler
    public void listener (OrderEntity orderEntity, Channel channel, Message message){
        System.out.println("收到关单信息,准备关闭订单" + orderEntity.getOrderSn());
        // 手动ACK
        try{
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }catch (Exception exception){
                System.out.println(e + ":{" +exception.getMessage() + "}");
            }
        }
    }
}
